﻿

namespace Test
 module Merge = 

    open System
    open System.Windows
    open System.Windows.Media
    open System.Windows.Shapes
    open System.Windows.Controls
    open FsSignals.Signal
      
    module NoGlicthes = 
        type Model = 
            {
                inputB : Button
                counterTB : TextBox
                firsResTB : TextBox
                sndResTB : TextBox
                resultLB : ListBox

                resetB : Button
            }
        
        let resetModel model = 
            model.inputB.Content <- "Push Me"
            model.counterTB.Text <- ""
            model.firsResTB.Text <- ""
            model.sndResTB.Text <- ""
            model.resultLB.Items.Clear()
            model.resetB.Content <- "Start Again"
            model

        let initPanel () = 
            let model =
              {
                inputB = new Button()
                counterTB = new TextBox()
                firsResTB = new TextBox()
                sndResTB = new TextBox()
                resultLB = new ListBox()

                resetB = new Button()
              }
            
            resetModel model

            let sp1 = new StackPanel()
            sp1.Margin <- new Thickness(10.0)
            let sp = new StackPanel()
            sp.Orientation <- Orientation.Horizontal 
            sp.HorizontalAlignment <- HorizontalAlignment.Left
            sp.Children.Add(model.inputB)
            sp.Children.Add(model.counterTB)
            sp.Children.Add(model.firsResTB)
            sp.Children.Add(model.sndResTB)
            sp.Children.Add(model.resultLB)
            sp.Children.Add(model.resetB)

            sp1.Children.Add(sp)

            (sp1, model)


        let makeNoGlitchPanel () =
            let (panel, model) = initPanel ()
            
            let rec engine() =
                resetModel model
                let inputSig = sourceEvent  model.inputB.Click --> (fun v -> v+1)
                let counterSig = stepAccumSig 0 inputSig
                counterSig =>> fun v ->    
                    model.counterTB.Text <- (sprintf "%A" v)

                let firstResSig = counterSig =>> ((*) 2)
                
                firstResSig =>> fun v ->    
                    model.firsResTB.Text <-  (sprintf "%A" v)

                let sndResSig = counterSig =>> ((+) 3)

                sndResSig =>> fun v ->    
                    model.sndResTB.Text <-  (sprintf "%A" v)

                let resSig = (+) <.> firstResSig <*> sndResSig
                resSig =>> fun v ->
                    model.resultLB.Items.Add(v)

                resSig =>> fun v -> printf "%A" v

                let resetSig = sourceEvent model.resetB.Click ==>> engine 
                switch resSig resetSig
            engine();
            panel